import './SetStartConfig.scss'
import { v4 } from 'uuid'

import { useState } from 'react'
import { useRequest } from 'alova/client'
import { useEventEmitter, useMount } from 'ahooks'
import { Skeleton, Button, Result, App, FloatButton, Tooltip, Radio } from 'antd'

import { Http } from '../../Utils/Api'
import { AdminRouter } from '../../Config/default'
import SmallWindow from '../../Page/Other/SmallWindow'
import { Encrypt, Decrypt } from '../../Utils/IndexedDB'
import StartTopConfig from '../../Page/Other/StartTopConfig'
import StartBackConfig from '../../Page/Other/StartBackConfig'
import { modelStore, drawerStore } from '../../Config/zustand'

import {
    GroupOutlined,
    SlidersOutlined,
    InsertRowAboveOutlined,
    SisternodeOutlined,
    SettingOutlined,
    SaveOutlined,
    CreditCardOutlined,
    ColumnHeightOutlined
} from '@ant-design/icons'

const defaultData = {
    backConfig: AdminRouter.BackConfigData,
    routerConfig: [],
    topConfig: {},
    navConfig: AdminRouter.StartNavConfig,
    smallWindow: AdminRouter.StartSmallWindow,
    scrollConfig: AdminRouter.StartScrollConfig
}

const { port } = window.location

const optionsBtnList = [
    { uuid: 1, label: '背景设置', icon: <GroupOutlined /> },
    { uuid: 2, label: '路由设置', icon: <SisternodeOutlined /> },
    { uuid: 3, label: '头部设置', icon: <InsertRowAboveOutlined /> },
    { uuid: 4, label: '导航设置', icon: <SlidersOutlined /> },
    { uuid: 5, label: '小窗设置', icon: <CreditCardOutlined /> },
    { uuid: 6, label: '滚动设置', icon: <ColumnHeightOutlined /> },
    { uuid: 7, label: '保存数据', icon: <SaveOutlined /> },
]

const SetStartConfig = () => {
    const { updateModel } = modelStore()
    const { updateDrawer } = drawerStore()
    const { message, modal, notification } = App.useApp()

    // 获取基础配置
    // 获取路由配置
    const { send } = useRequest(data => Http(data), { immediate: false })
    const StartEvent = useEventEmitter()
    const WindowEvent = useEventEmitter()
    const ScrollEvent = useEventEmitter()
    const NavEvent = useEventEmitter()

    const [Open, setOpen] = useState(false)
    const [Start, setStart] = useState(false)
    const [Loading, setLoading] = useState(false)

    const [Config, setConfig] = useState()

    const [PageStatus, setPageStatus] = useState('home')

    const getData = () => {
        send({ method: 'get', url: 'dictionary/GetJsonInfoByUuid', params: { uuid: 'StartConfig/index' } })
            .then(async res => {
                setConfig(await Decrypt(res))
                setStart(true)
            }).catch(() => {
                setStart(true)
            })
    }

    const setData = async () => {
        const data = Config ? Config : defaultData
        console.log('保存数据', data)
        setLoading()
        send({
            method: 'post',
            url: 'dictionary/SaveJsonInfoByUuid',
            params: {
                uuid: 'StartConfig/index',
                content: JSON.stringify(await Encrypt(data))
            }
        })
            .then(res => {
                setConfig(data)
                setLoading(false)
                notification.success({ key: 'start', message: '保存成功!', description: '数据已保存!', showProgress: true })
            }).catch(() => {
                notification.error({ key: 'start', message: '保存失败!', description: '请确认网络状态或联系管理员解决!', showProgress: true })
            })
    }

    const onButtonClick = async (uuid) => {
        switch (uuid) {
            case 1:
                updateDrawer({
                    type: 'SetStartData',
                    width: 480,
                    title: '背景设置',
                    mask: false,
                    data: { type: 'A01', StartEvent, config: Config.backConfig }
                })
                break;
            case 2:
                updateDrawer({
                    type: 'SetStartData',
                    width: 480,
                    title: '大屏路由',
                    mask: false,
                    data: { type: 'A02', StartEvent, config: Config }
                })
                break;
            case 3:
                updateDrawer({
                    type: 'AddFormData',
                    width: 480,
                    title: '头部设置',
                    mask: false,
                    data: { type: 'AddStartTop', AddEvnet: StartEvent, Initial: Config.topConfig }
                })
                break;
            case 4:
                updateDrawer({
                    type: 'AddFormData',
                    width: 480,
                    title: '导航设置',
                    mask: false,
                    data: { type: 'AddStartNav', AddEvnet: NavEvent, Initial: Config.navConfig }
                })
                break;
            case 5:
                updateDrawer({
                    type: 'AddFormData',
                    width: 480,
                    title: '小窗设置',
                    mask: false,
                    data: { type: 'AddStartWindow', AddEvnet: WindowEvent, Initial: Config.smallWindow }
                })
                break;
            case 6:
                updateDrawer({
                    type: 'AddFormData',
                    width: 480,
                    title: '滚动设置',
                    mask: false,
                    data: { type: 'AddStartScroll', AddEvnet: ScrollEvent, Initial: Config.scrollConfig }
                })
                break
            case 7:
                setData()
                break

            default:
                break;
        }
    }

    const CallBackFunc = (e) => {
        const { type, data } = e
        // console.log(type, data)
        const MapReturn = new Map([
            ['onChangeBack', () => setConfig({ ...Config, backConfig: data })],
            ['onSaveConfig', () => setConfig({ ...data })],
            ['onFormBack', () => {
                notification.success({ key: 'start', message: '保存成功!', description: '头部设置成功!', showProgress: true })
                setConfig(e => ({ ...e, topConfig: data }))
            }]
        ])
        const func = MapReturn.get(type)
        return func && func()
    }

    StartEvent.useSubscription(CallBackFunc)

    NavEvent.useSubscription(val => {
        if (val.type === 'onFormBack') {
            notification.success({ key: 'start', message: '保存成功!', description: '导航设置成功!', showProgress: true })
            setConfig(e => ({ ...e, navConfig: val.data }))
        }
    })

    WindowEvent.useSubscription(val => {
        if (val.type === 'onFormBack') {
            notification.success({ key: 'start', message: '保存成功!', description: '小窗设置成功!', showProgress: true })
            setConfig(e => ({ ...e, smallWindow: val.data }))
        }
    })
    ScrollEvent.useSubscription(val => {
        if (val.type === 'onFormBack') {
            notification.success({ key: 'start', message: '保存成功!', description: '滚动条设置成功!', showProgress: true })
            setConfig(e => ({ ...e, scrollConfig: val.data }))
        }
    })

    useMount(getData)

    return (
        <div className='SetStartConfig'>
            {Start ?
                Config ?
                    <div className='StartPage'>
                        {/* {console.log('基础配置信息', Config.routerConfig)} */}
                        <div className='StartPage__Config'>
                            <StartBackConfig config={Config.backConfig} />
                            <StartTopConfig PageStatus={PageStatus} topConfig={Config.topConfig} routerConfig={Config.routerConfig} />
                            <div className='outletConfig'>
                                <div className='outlet'>
                                    <SmallWindow config={Config.smallWindow} title='小窗演示'>
                                        {(() => {
                                            const style = {
                                                '--width': Config.scrollConfig.scroll_width + 'px',
                                                '--height': Config.scrollConfig.scroll_height + 'px',
                                                '--radius': Config.scrollConfig.scroll_radius + 'px',
                                                '--track': Config.scrollConfig.scroll_track,
                                                '--thumb': Config.scrollConfig.scroll_thumb,
                                                '--hover': Config.scrollConfig.scroll_hover,
                                            }
                                            const { top_height } = Config.smallWindow
                                            return (
                                                <div className='Scroll' style={style}>
                                                    <div className='Text'>滚动条展示</div>
                                                    <div className='Options' style={{ top: -top_height }}>
                                                        <Radio.Group defaultValue="home" buttonStyle="solid" onChange={e => setPageStatus(e.target.value)}>
                                                            <Radio.Button value="home">首页</Radio.Button>
                                                            <Radio.Button value="page">页面</Radio.Button>
                                                        </Radio.Group>
                                                    </div>
                                                </div>
                                            )
                                        })()}
                                    </SmallWindow>
                                </div>
                            </div>
                        </div>
                        <FloatButton.Group
                            type="primary"
                            trigger="click"
                            shape="square"
                            open={Open}
                            onClick={e => setOpen(!Open)}
                            style={{ insetInlineEnd: 24 }}
                            icon={<SettingOutlined />}
                        >
                            {optionsBtnList.map(item =>
                                <Tooltip key={item.uuid} title={item.label} placement="left">
                                    <FloatButton icon={item.icon} onClick={() => onButtonClick(item.uuid)} />
                                </Tooltip>
                            )}
                        </FloatButton.Group>
                    </div> :
                    <div className='Result'>
                        <Result
                            status="404"
                            title="为获取到位置文件,是否生成新的配置文件?"
                            extra={port && <Button type="primary" loading={Loading} onClick={setData}>生成配置文件</Button>}
                        />
                    </div> :
                <Skeleton active paragraph={{ rows: 24 }} />
            }
        </div>
    );
};

export default SetStartConfig;